package com.mingtu.guards.activity;

import android.os.Build;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.entity.TabEntity;
import com.mingtu.common.utils.CalendarPickerUtils;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.EquiSingleChoiceTextAdapter;
import com.mingtu.guards.adapter.FliteDequAdapter;
import com.mingtu.guards.adapter.TabbarAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.InfraredDequiBean;
import com.mingtu.guards.fragment.InfraredRecordFragment1;
import com.mingtu.guards.fragment.InfraredRecordFragment2;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.guards.view.FilterCancleView;
import com.mingtu.guards.view.FilterSureView;
import com.mingtu.guards.view.TimeFilterView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

public class InfraredRecordPictureActivity extends MyBaseActivity {
    @BindView(R.id.layout_right_drawer)
    LinearLayout layoutRightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.tab_nav)
    CommonTabLayout tabNav;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.recycler_dequ)
    RecyclerView recyclerDequ;
    @BindView(R.id.layout_dequ)
    LinearLayout layoutDequ;
    @BindView(R.id.layout_depart)
    LinearLayout layoutDepart;
    @BindView(R.id.recycler_depart)
    RecyclerView recyclerDepart;
    @BindView(R.id.time_filter_time)
    TimeFilterView timeFilterTime;
    @BindView(R.id.filter_cancle_view)
    FilterCancleView filterCancleView;
    @BindView(R.id.filter_sure_view)
    FilterSureView filterSureView;
    private String cameraName;
    private String beginTime = null;
    private String endTime = null;
    private static final String[] mTitles = {"识别鉴定", "实时抓拍"};
    private static final int[] mSeleIcons = {R.mipmap.icon_pic_auth_people_selected, R.mipmap.icon_pic_auth_all_selected};
    private static final int[] mNormalIcons = {R.mipmap.icon_pic_auth_people_normal, R.mipmap.icon_pic_auth_all_normal};
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private InfraredRecordFragment1 infraredRecordFragment1;
    private InfraredRecordFragment2 infraredRecordFragment2;
    private FliteDequAdapter fliteDequAdapter;
    private boolean dequFlag = false; //记录设备筛选是否展开
    private List<InfraredDequiBean.DataBean.ListBean> dataBeans;
    private List<InfraredDequiBean.DataBean.ListBean> myDataBeans;
    private List<String> deptNameList;
    private EquiSingleChoiceTextAdapter filteDepartAdapter;
    private List<InfraredDequiBean.DataBean.ListBean> deptEquiList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_infrared_record_picture;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("实时监测");
//        setTitleBarBackground(getResources().getDrawable(com.mingtu.center.R.drawable.titlebar_line_bottom));
//        showTopRightImg(R.mipmap.icon_filte_black);
    }

    @Override
    protected void initData() {
        //将时间数据初始化
        SPStaticUtils.put(MySPTools.picFliteBeginTime, "");
        SPStaticUtils.put(MySPTools.picFliteEndTime, "");
        SPStaticUtils.put(MySPTools.picFliteType, 0);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void getData() {
        cameraName = getIntent().getStringExtra("cameraName");


        if (StringUtils.isEmpty(cameraName)) { //实时监测进入此界面
            layoutDequ.setVisibility(View.VISIBLE);

            //-----------------------红外设备------------------

            //部门列表
            FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
            flm1.setFlexWrap(FlexWrap.WRAP);
            flm1.setFlexDirection(FlexDirection.ROW);
            flm1.setAlignItems(AlignItems.STRETCH);
            flm1.setJustifyContent(JustifyContent.FLEX_START);
            recyclerDepart.setLayoutManager(flm1);

            filteDepartAdapter = new EquiSingleChoiceTextAdapter(BaseApplication.getBaseApplication(), null);
            recyclerDepart.setAdapter(filteDepartAdapter);
            filteDepartAdapter.setOnItemClickListener(new EquiSingleChoiceTextAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    filteDepartAdapter.upData(position);
                    if (deptNameList != null && deptNameList.size() > 0) {
                        String currentDeptName = deptNameList.get(position);
                        List<InfraredDequiBean.DataBean.ListBean> equiList = getDeptEqui(currentDeptName);
                        fliteDequAdapter.upData(equiList);
                    }
                }
            });


            //设备列表
            FlexboxLayoutManager flm2 = new FlexboxLayoutManager(this);
            flm2.setFlexWrap(FlexWrap.WRAP);
            flm2.setFlexDirection(FlexDirection.ROW);
            flm2.setAlignItems(AlignItems.STRETCH);
            flm2.setJustifyContent(JustifyContent.FLEX_START);
            recyclerDequ.setLayoutManager(flm2);

            fliteDequAdapter = new FliteDequAdapter(context, null);
            recyclerDequ.setAdapter(fliteDequAdapter);
            infraredRecordFragment1 = InfraredRecordFragment1.getInstance(cameraName, fliteDequAdapter);
            infraredRecordFragment2 = InfraredRecordFragment2.getInstance(cameraName, fliteDequAdapter);
            getDequiList();

        } else {
            layoutDequ.setVisibility(View.GONE);
            layoutDepart.setVisibility(View.GONE);
            setModuleTitle(cameraName + "拍摄列表");
            infraredRecordFragment1 = InfraredRecordFragment1.getInstance(cameraName, null);
            infraredRecordFragment2 = InfraredRecordFragment2.getInstance(cameraName, null);
        }


        mFragments.add(infraredRecordFragment1);
        mFragments.add(infraredRecordFragment2);

        viewPager.setOffscreenPageLimit(2);//需要设置此值
        viewPager.setAdapter(new TabbarAdapter(getSupportFragmentManager(), mFragments));
        viewPager.addOnPageChangeListener(onPageChangeListener);
        for (int i = 0; i < mTitles.length; i++) {
//            mTabEntities.add(new TabEntity(mTitles[i], mSeleIcons[i], mNormalIcons[i]));
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        tabNav.setTabData(mTabEntities);
        tabNav.setOnTabSelectListener(onTabSelectListener);
        timeFilterTime.setOnTimeResultListener(new TimeFilterView.OnTimeResultListener() {
            @Override
            public void onResult(Date startDate, Date endDate) {
                beginTime = UIUtils.getTime3(startDate);
                endTime = UIUtils.getTime3(endDate);
                SPStaticUtils.put(MySPTools.picFliteBeginTime, beginTime);
                SPStaticUtils.put(MySPTools.picFliteEndTime, endTime);
            }
        });

        filterCancleView.setOnClickListener(new FilterCancleView.OnClickListener() {
            @Override
            public void onClickCancel() {
                closeDrawers();
            }
        });

        filterSureView.setOnClickListener(new FilterSureView.OnClickListener() {
            @Override
            public void onClickReset() {
                closeDrawers();
                resetData();
                CalendarPickerUtils.getInstance().resetData();
            }

            @Override
            public void onClickSure() {
//                if (fliteDequAdapter == null) {
//                    if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
//                        ToastUtils.showLong("请选择时间！");
//                        return;
//                    }
//                } else {
//                    List<String> dequNameList = fliteDequAdapter.getDequNameList();
//                    if (dequNameList.size() == 0) {
//                        ToastUtils.showLong("请选择设备！");
//                        return;
//                    }
//                }

                closeDrawers();

                boolean isResumed1 = infraredRecordFragment1.isResumed(); //判断fragment是否已经加载
                boolean isResumed2 = infraredRecordFragment2.isResumed();

                if (isResumed1) {
                    infraredRecordFragment1.flitePic(fliteDequAdapter);
                }
                if (isResumed2) {
                    infraredRecordFragment2.flitePic(fliteDequAdapter);
                }
            }
        });


    }

    @OnClick({R.id.iv_filte})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_filte:
                boolean isOpen = drawerLayout.isDrawerOpen(layoutRightDrawer);
                if (isOpen) {
                    closeDrawers();
                } else {
                    openDrawer();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPStaticUtils.remove(MySPTools.picFliteBeginTime);
        SPStaticUtils.remove(MySPTools.picFliteEndTime);
        SPStaticUtils.remove(MySPTools.picFliteType);
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //处理完之后刷新数据
        String message = event.getMessgae();
        if (message.equals(MyConstant.REFRESH_INFRARED_DATA)) {
            infraredRecordFragment1.refresh();
            infraredRecordFragment2.refresh();
        }

    }

    private void resetData() {
        SPStaticUtils.put(MySPTools.picFliteBeginTime, "");
        SPStaticUtils.put(MySPTools.picFliteEndTime, "");

        beginTime = null;
        endTime = null;

        timeFilterTime.resetData();

        if (fliteDequAdapter != null) { //显示设备筛选的时候不为null
            fliteDequAdapter.resetData();
        }

        if (filteDepartAdapter != null) {
            filteDepartAdapter.resetData();
        }

        infraredRecordFragment1.resetData();
        infraredRecordFragment2.resetData();


    }


    /**
     * 关闭侧边栏
     */
    public void closeDrawers() {
        drawerLayout.closeDrawer(layoutRightDrawer, true);
    }

    /**
     * 打开侧边栏
     */
    public void openDrawer() {
        drawerLayout.openDrawer(layoutRightDrawer);
    }


    /**
     * 红外设备信息
     */
    private void getDequiList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", 500);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_DEQUI_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            InfraredDequiBean infraredDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                infraredDequiBean = new InfraredDequiBean();
                                infraredDequiBean = gson.fromJson(result, InfraredDequiBean.class);
                                dataBeans = infraredDequiBean.getData().getList();
                                if (dataBeans != null && dataBeans.size() > 0) {
                                    deptNameList = dataBeans.stream().map(InfraredDequiBean.DataBean.ListBean::getDeptName).distinct().collect(Collectors.toList());
                                    if (deptNameList.size() > 0) {
                                        filteDepartAdapter.upData(deptNameList);
                                    }
                                    //初始化部门下的设备列表
                                    deptEquiList = dataBeans;
                                    fliteDequAdapter.upData(dataBeans);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }


    private OnTabSelectListener onTabSelectListener = new OnTabSelectListener() {
        @Override
        public void onTabSelect(int position) {
            viewPager.setCurrentItem(position, false);
            SPStaticUtils.put(MySPTools.picFliteType, position);
        }

        @Override
        public void onTabReselect(int position) {

        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            tabNav.setCurrentTab(position);
            SPStaticUtils.put(MySPTools.picFliteType, position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**
     * 根据保护区名字查询设备
     *
     * @param currentDeptName
     * @return
     */
    private List<InfraredDequiBean.DataBean.ListBean> getDeptEqui(String currentDeptName) {
        deptEquiList = new ArrayList<>();
        if (dataBeans != null && dataBeans.size() > 0) {
            for (InfraredDequiBean.DataBean.ListBean listBean : this.dataBeans) {
                String deptName = listBean.getDeptName();
                if (currentDeptName.equals(deptName)) {
                    deptEquiList.add(listBean);
                }
            }
            return deptEquiList;
        } else {
            return deptEquiList;
        }
    }

}